/*
 * Copyright 2007 Rob Nielsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.proxymatic.core;

import junit.framework.AssertionFailedError;
import junit.framework.TestCase;

public class FaultTestCase extends TestCase {
    public Throwable assertThrows(Class expectedException, Block block) {
        return assertThrows(expectedException, null, block);
    }

    public Throwable assertThrows(Class expectedException, String message, Block block) {
        try {
            block.run();
            fail("Expected exception " + expectedException + " was not thrown");
            return null;
        } catch (AssertionFailedError e) {
            throw e;
        } catch (Throwable th) {
            assertEquals("Wrong exception thrown: " + th, expectedException, th.getClass());
            if (message != null) {
                assertContains(message, th.getMessage());
            }
            return th;
        }
    }

    private void assertContains(String expectedSubstring, String actual) {
        if (actual == null || actual.indexOf(expectedSubstring) == -1) {
            fail(actual + " did not contain the substring " + expectedSubstring);
        }
    }

    public static interface Block {
        public void run() throws Throwable;
    }
}
